<?php
/**
 * @version		$Id: home.php 20110729 muinx $
 * @copyright	Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
 * @license		GNU General Public License version 2 or later; see LICENSE.txt
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

/**
 * This models supports retrieving lists of articles.
 *
 * @package		Joomla.Site
 * @subpackage	com_je_youtube
 * @since		1.6
 */
class Je_YoutubeModelHome extends JModelList
{
	/**
	 * Method to auto-populate the model state.
	 *
	 * Note. Calling getState in this method will result in recursion.
	 *
	 * @return	void
	 * @since	1.6
	 */
	protected function populateState($ordering = 'ordering', $direction = 'ASC')
	{
		$app = JFactory::getApplication();

		// List state information
		//$value = $app->getUserStateFromRequest('global.list.limit', 'limit', $app->getCfg('list_limit'));
		$value = JRequest::getUInt('limit', $app->getCfg('list_limit', 0));
		$this->setState('list.limit', $value);
	}

	/**
	 * Get the master query for retrieving a list of articles subject to the model state.
	 *
	 * @return	JDatabaseQuery
	 * @since	1.6
	 */
	function getListQuery()
	{
		// Create a new query object.
		$db = $this->getDbo();
		$query = $db->getQuery(true);
		
		$catId = JRequest::getVar('catid');

		// Select the required fields from the table.
		$query->select(
			$this->getState(
				'list.select',
				'a.*'
			)
		);

		$query->from('#__je_youtube AS a');

		// Join over the categories.
		$query->select('c.title AS category_title, c.alias AS category_alias');
		$query->join('LEFT', '#__categories AS c ON c.id = a.catid');
		
		// Filter by start and end dates.
		$nullDate 	= $db->Quote($db->getNullDate());
		$nowDate 	= $db->Quote(JFactory::getDate()->toMySQL());
		
		$query->where('a.state = 1');
		$query->where('(a.publish_up = '.$nullDate.' OR a.publish_up <= '.$nowDate.')');
		$query->where('(a.publish_down = '.$nullDate.' OR a.publish_down >= '.$nowDate.')');
		
		if($catId)
			$query->where('a.catid IN (
								SELECT cat.id 
								FROM #__categories cat, (SELECT * from #__categories where id = "'.$catId.'") as viewa 
								WHERE cat.extension = "com_je_youtube" and (cat.id = "'.$catId.'" or (cat.lft > viewa.lft and cat.rgt < viewa.rgt))
							)');
		
		$query->order('id DESC');
		
		#echo str_replace('#__', 'jos_', $query);
		return $query;
	}
}
